<template>
  <div class="">
    <!-- 顶部卡片统计 -->
    <el-row :gutter="20" class="stat-cards">
      <el-col :xs="24" :sm="6" :md="4">
        <div class="stat-card">
          <div class="stat-icon">
            <i class="el-icon-warning" style="color: #F56C6C;"></i>
          </div>
          <div class="stat-info">
            <div class="stat-value" style="color: #F56C6C;">{{needUrgentRepair}}个</div>
            <div class="stat-label">需紧急修复漏洞</div>
          </div>
<!--          <div class="stat-trend up">-->
<!--            <i class="el-icon-caret-top"></i>-->
<!--            <span>2.5%</span>-->
<!--          </div>-->
        </div>
      </el-col>
      <el-col :xs="24" :sm="6" :md="4">
        <div class="stat-card">
          <div class="stat-icon">
            <i class="el-icon-success" style="color: #67C23A;"></i>
          </div>
          <div class="stat-info">
            <div class="stat-value" style="color: #67C23A;">{{unrepair}}个</div>
            <div class="stat-label">未完成修复的漏洞</div>
          </div>
<!--          <div class="stat-trend down">-->
<!--            <i class="el-icon-caret-bottom"></i>-->
<!--            <span>1.8%</span>-->
<!--          </div>-->
        </div>
      </el-col>
      <el-col :xs="24" :sm="6" :md="4">
        <div class="stat-card">
          <div class="stat-icon">
            <i class="el-icon-s-platform" style="color: #409EFF;"></i>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{existedVulHosts}}台</div>
            <div class="stat-label">存在漏洞的服务器</div>
          </div>
<!--          <div class="stat-trend stable">-->
<!--            <i class="el-icon-minus"></i>-->
<!--            <span>持平</span>-->
<!--          </div>-->
        </div>
      </el-col>
      <el-col :xs="24" :sm="6" :md="4">
        <div class="stat-card">
          <div class="stat-icon">
            <i class="el-icon-monitor" style="color: #E6A23C;"></i>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{allHandle}}台</div>
            <div class="stat-label">修复成功待重启主机</div>
          </div>
<!--          <div class="stat-trend up">-->
<!--            <i class="el-icon-caret-top"></i>-->
<!--            <span>1.2%</span>-->
<!--          </div>-->
        </div>
      </el-col>
      <el-col :xs="24" :sm="6" :md="4">
        <div class="stat-card">
          <div class="stat-icon">
            <i class="el-icon-lock" style="color: #E6A23C;"></i>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{todayHandle}}/{{allHandle}}个</div>
            <div class="stat-label">今日/累计处理漏洞</div>
          </div>
<!--          <div class="stat-trend up">-->
<!--            <i class="el-icon-caret-top"></i>-->
<!--            <span>1.2%</span>-->
<!--          </div>-->
        </div>
      </el-col>
      <el-col :xs="24" :sm="6" :md="4">
        <div class="stat-card">
          <div class="stat-icon">
            <i class="el-icon-mobile" style="color: #E6A23C;"></i>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{supported}}个</div>
            <div class="stat-label">已支持漏洞</div>
          </div>
<!--          <div class="stat-trend up">-->
<!--            <i class="el-icon-caret-top"></i>-->
<!--            <span>1.2%</span>-->
<!--          </div>-->
        </div>
      </el-col>
    </el-row>

    <!-- 主机防护状态 -->
    <div class="security-status">
      <div class="status-left">
        <div class="status-section">
          <div class="section-header">
            <h3 class="section-title">
              <i class="el-icon-s-platform"></i>
              主机防护
            </h3>
            <el-button-group>
              <el-button size="small" icon="el-icon-refresh">刷新</el-button>
              <el-button size="small" icon="el-icon-setting">设置</el-button>
            </el-button-group>
          </div>
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="status-item">
                <span class="item-label">网络防护:</span>
                <span class="item-value">
                  <el-tag size="small" type="success">
                    正常
                    <i class="el-icon-check"></i>
                  </el-tag>
                  <el-tooltip content="网络防护运行正常" placement="top">
                    <i class="el-icon-info status-info"></i>
                  </el-tooltip>
                </span>
              </div>
              <div class="status-item">
                <span class="item-label">主机防护:</span>
                <span class="item-value">
                  <el-tag size="small" type="success">
                    正常
                    <i class="el-icon-check"></i>
                  </el-tag>
                  <el-tooltip content="主机防护运行正常" placement="top">
                    <i class="el-icon-info status-info"></i>
                  </el-tooltip>
                </span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="status-item">
                <span class="item-label">网络防护版本:</span>
                <span class="item-value">
                  网络防护高级版
                  <el-button type="text" size="mini">升级</el-button>
                </span>
              </div>
              <div class="status-item">
                <span class="item-label">主机防护版本:</span>
                <span class="item-value">
                  主机防护高级版
                  <el-button type="text" size="mini">升级</el-button>
                </span>
              </div>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="status-item">
                <span class="item-label">安全状态:</span>
                <span class="item-value warning">
                  <i class="el-icon-warning"></i>
                  11项待处理
                </span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="status-item">
                <span class="item-label">安全策略:</span>
                <span class="item-value">
                  <el-button type="text">查看详情</el-button>
                  <el-tooltip content="当前应用的安全策略" placement="top">
                    <i class="el-icon-info status-info"></i>
                  </el-tooltip>
                </span>
              </div>
            </el-col>
          </el-row>
        </div>
      </div>
      <div class="status-right">
        <div ref="securityScore" class="security-score"></div>
        <div ref="securityTrend" class="security-trend"></div>
      </div>
    </div>
    <el-card class="table-card" shadow="hover">
    <el-tabs v-model="activeTabs" @tab-click="handleTabClick">
      <el-tab-pane name="config">
          <span slot="label">
            <i class="el-icon-cpu"></i> 主机漏洞
            <el-tag type="danger" size="small" class="count-tag">
            {{ this.total }}个待处理
          </el-tag>
          </span>
          <div class="filter-bar">
            <div class="filter-left">
              <el-select v-model="urgencyLevel" placeholder="紧急程度" size="small">
                <el-option label="全部" value="all">
                  <i class="el-icon-warning" style="color: #909399;"></i> 全部
                </el-option>
                <el-option label="紧急" value="urgent">
                  <i class="el-icon-warning" style="color: #F56C6C;"></i> 紧急
                </el-option>
                <el-option label="高危" value="high">
                  <i class="el-icon-warning" style="color: #E6A23C;"></i> 高危
                </el-option>
                <el-option label="中危" value="medium">
                  <i class="el-icon-warning" style="color: #409EFF;"></i> 中危
                </el-option>
                <el-option label="低危" value="low">
                  <i class="el-icon-info" style="color: #909399;"></i> 低危
                </el-option>
              </el-select>
              <el-input
                v-model="searchQuery"
                placeholder="搜索漏洞名称、编号"
                prefix-icon="el-icon-search"
                size="small"
                clearable
              >
                <el-button slot="append" icon="el-icon-search"></el-button>
              </el-input>
            </div>
          </div>
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button
                type="primary"
                size="small"
                icon="el-icon-cpu"
                :disabled="!selectedVulnerabilities.length"
                @click="handleBatchFix"
              >批量修复</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="primary"
                size="small"
                icon="el-icon-refresh"
                :loading="loading"
                @click="refreshData"
              >刷新</el-button>
            </el-col>
            <el-button
              type="primary"
              size="small"
              icon="el-icon-download"
              @click="exportData"
            >导出</el-button>
            <el-col :span="1.5">
            </el-col>
          </el-row>
          <div v-if="false" style="text-align: right; margin-bottom: 10px; color: #909399;">
            Debug: Total events: {{ eventPagination.total }}
          </div>
          <el-table
            :data="filteredVulnerabilities"
            style="width: 100%"
            v-loading="loading"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column prop="name" label="漏洞名称" min-width="400">
              <template slot-scope="scope">
                <div class="vulnerability-name">
                  <el-tooltip :content="scope.row.vul_name" placement="top">
                    <span class="name-text">{{ scope.row.vul_name }}</span>
                  </el-tooltip>
                  <el-tag
                    v-if="scope.row.isNew"
                    size="mini"
                    type="danger"
                    class="new-tag"
                  >新</el-tag>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="urgencyLevel" label="紧急程度" width="120">
              <template slot-scope="scope">
                <el-tag
                  :type="getUrgencyType(scope.row.repair_priority)"
                  size="small"
                  effect="dark"
                >
                  <i class="el-icon-warning"></i>
                  {{ getUrgencyName(scope.row.repair_priority) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="urgencyLevel" label="漏洞编号" width="120">
              <template slot-scope="scope">
                <div class="vulnerability-name">
                  <el-tooltip :content="scope.row.vul_id" placement="top">
                    <span class="name-text">{{ scope.row.vul_id }}</span>
                  </el-tooltip>
                </div>
              </template>
            </el-table-column>
            <!--        <el-table-column prop="status" label="状态" width="120">-->
            <!--          <template slot-scope="scope">-->
            <!--            <el-tag-->
            <!--              :type="getStatusType(scope.row.status)"-->
            <!--              size="small"-->
            <!--              effect="plain"-->
            <!--            >-->
            <!--              <i :class="getStatusIcon(scope.row.status)"></i>-->
            <!--              {{ scope.row.status }}-->
            <!--            </el-tag>-->
            <!--          </template>-->
            <!--        </el-table-column>-->
            <el-table-column prop="lastFound" label="最后发现时间" width="180">
              <template slot-scope="scope">
                <i class="el-icon-time"></i>
                {{ formatTime(scope.row.scan_time) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="250" fixed="right">
              <template slot-scope="scope">
                <el-button-group>
                  <el-button
                    type="primary"
                    size="mini"
                    @click="handleFix(scope.row)"
                  >修复</el-button>
                  <el-button
                    type="primary"
                    size="mini"
                    @click="handleDetails(scope.row)"
                  >详情</el-button>
                  <el-dropdown trigger="click" @command="(command) => handleMore(command, scope.row)">
                    <el-button type="primary" size="mini">
                      更多<i class="el-icon-arrow-down el-icon--right"></i>
                    </el-button>
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item command="ignore">忽略</el-dropdown-item>
                      <el-dropdown-item command="report">报告问题</el-dropdown-item>
                      <el-dropdown-item command="history">修复历史</el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                </el-button-group>
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getVulnerability"
          />

      </el-tab-pane>

      <el-tab-pane name="idle">
        <span slot="label">
          <i class="el-icon-timer"></i> 主机警告
          <el-tag type="danger" size="small" class="count-tag">
            {{ securityEvents && securityEvents.filter ? securityEvents.filter(item => item.handle_status === 'unhandled').length : 0 }}个待处理
          </el-tag>
        </span>

        <!-- 工具栏 -->
        <div class="filter-bar" v-if="securityEvents.length > 0">
          <div class="filter-left">
            <el-select v-model="securityLevel" placeholder="告警级别" size="small" style="width: 120px; margin-right: 10px;">
              <el-option label="全部" value="all">
                <i class="el-icon-warning" style="color: #909399;"></i> 全部
              </el-option>
              <el-option label="高危" value="High">
                <i class="el-icon-warning" style="color: #F56C6C;"></i> 高危
              </el-option>
              <el-option label="中危" value="Medium">
                <i class="el-icon-warning" style="color: #E6A23C;"></i> 中危
              </el-option>
              <el-option label="低危" value="Low">
                <i class="el-icon-info" style="color: #409EFF;"></i> 低危
              </el-option>
            </el-select>

            <el-select v-model="handleStatus" placeholder="处理状态" size="small" style="width: 120px; margin-right: 10px;">
              <el-option label="全部" value="all"></el-option>
              <el-option label="未处理" value="unhandled"></el-option>
              <el-option label="已处理" value="handled"></el-option>
            </el-select>

            <el-input
              v-model="eventSearchQuery"
              placeholder="搜索告警名称、主机名"
              prefix-icon="el-icon-search"
              size="small"
              clearable
              style="width: 220px;"
            >
            </el-input>
          </div>

          <div class="filter-right">
            <el-button type="primary" size="small" icon="el-icon-refresh" @click="refreshEvents">刷新</el-button>
            <el-button
              type="success"
              size="small"
              icon="el-icon-check"
              :disabled="!selectedEvents || selectedEvents.length === 0"
              @click="batchMarkAsHandled"
            >批量处理</el-button>
          </div>
        </div>

        <!-- 告警列表 -->
        <div v-if="securityEvents.length > 0">
          <el-table
            :data="filteredSecurityEvents || []"
            style="width: 100%"
            @selection-change="handleEventSelectionChange"
            v-loading="eventsLoading"
          >
            <el-table-column type="selection" width="55" align="center" />

            <el-table-column label="告警级别" width="90" align="center">
              <template slot-scope="{ row }">
                <el-tag :type="getSeverityType(row.severity)" size="small">
                  {{ getSeverityName(row.severity) }}
                </el-tag>
              </template>
            </el-table-column>

            <el-table-column label="告警名称" min-width="180">
              <template slot-scope="{ row }">
                <div class="event-name-cell">
                  <span class="event-name">{{ row.event_name }}</span>
                  <el-tooltip :content="row.event_abstract" placement="top">
                    <i class="el-icon-info-circle"></i>
                  </el-tooltip>
                </div>
              </template>
            </el-table-column>

            <el-table-column label="主机名/IP" min-width="280">
              <template slot-scope="{ row }">
                <div class="host-info">
                  <span class="host-name">{{ row.host_name }}</span>
                  <span class="host-ip">{{ row.public_ip}}(公){{row.private_ip }}(私)</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="攻击标识" width="180">
              <template slot-scope="{ row }">
                <span>异常行为</span>
              </template>
            </el-table-column>
            <el-table-column label="操作系统" width="180">
              <template slot-scope="{ row }">
                <span>{{ getOsInfo(row) }}</span>
              </template>
            </el-table-column>

            <el-table-column label="发生时间" min-width="170">
              <template slot-scope="{ row }">
                <span>{{ formatEventTime(row.occur_time) }}</span>
              </template>
            </el-table-column>

            <el-table-column label="处理状态" width="100" align="center">
              <template slot-scope="{ row }">
                <el-tag
                  :type="row.handle_status === 'unhandled' ? 'danger' : 'success'"
                  size="small"
                >
                  {{ row.handle_status === 'unhandled' ? '未处理' : '已处理' }}
                </el-tag>
              </template>
            </el-table-column>

            <el-table-column label="操作" width="180" fixed="right">
              <template slot-scope="{ row }">
                <el-button type="text" size="small" @click="viewEventDetails(row)">详情</el-button>
                <el-button
                  v-if="row.handle_status === 'unhandled'"
                  type="text"
                  size="small"
                  @click="markEventAsHandled(row)"
                >标记处理</el-button>
                <el-button
                  v-if="row.handle_status === 'unhandled'"
                  type="text"
                  size="small"
                  @click="ignoreEvent(row)"
                >忽略</el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <div class="pagination-container">
            <el-pagination
              @size-change="handleEventSizeChange"
              @current-change="handleEventCurrentChange"
              :current-page="eventPagination.currentPage"
              :page-sizes="[10, 20, 50, 100]"
              :page-size="eventPagination.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="eventPagination.total"
            ></el-pagination>
          </div>
        </div>

        <!-- 空状态 -->
        <div v-else class="empty-content">
          <i class="el-icon-bell"></i>
          <p>暂无主机告警数据</p>
        </div>

        <!-- 告警详情对话框 -->
        <el-dialog
          title="告警详情"
          :visible.sync="eventDetailsVisible"
          width="800px"
          :modal="false"
        >
          <div v-if="currentEvent" class="event-details">
            <div class="detail-header">
              <div class="detail-title">
                <span class="event-type-name">{{ currentEvent.event_name }}</span>
                <el-tag :type="getSeverityType(currentEvent.severity)" size="small">
                  {{ getSeverityName(currentEvent.severity) }}
                </el-tag>
              </div>
              <div class="detail-time">
                发生时间: {{ formatEventTime(currentEvent.occur_time) }}
              </div>
            </div>

            <el-divider></el-divider>

            <div class="detail-content">
              <el-descriptions :column="2" border>
                <el-descriptions-item label="告警ID">{{ currentEvent.event_id }}</el-descriptions-item>
                <el-descriptions-item label="主机名">{{ currentEvent.host_name }}</el-descriptions-item>
                <el-descriptions-item label="IP地址">{{ currentEvent.private_ip }}</el-descriptions-item>
                <el-descriptions-item label="操作系统">{{ getOsInfo(currentEvent) }}</el-descriptions-item>
                <el-descriptions-item label="处理状态" :span="2">
                  <el-tag :type="currentEvent.handle_status === 'unhandled' ? 'danger' : 'success'">
                    {{ currentEvent.handle_status === 'unhandled' ? '未处理' : '已处理' }}
                  </el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="告警摘要" :span="2">
                  {{ currentEvent.event_abstract }}
                </el-descriptions-item>
                <el-descriptions-item label="告警描述" :span="2">
                  {{ currentEvent.description }}
                </el-descriptions-item>
              </el-descriptions>

              <div class="detail-section">
                <h4>处理建议</h4>
                <div class="recommendation-content">
                  <p v-for="(line, index) in currentEvent.recommendation.split('\r\n')" :key="index">
                    {{ line }}
                  </p>
                </div>
              </div>

              <div class="detail-section" v-if="currentEvent.event_details">
                <h4>详细信息</h4>
                <el-collapse>
                  <el-collapse-item title="查看详细信息">
                    <pre class="event-details-json">{{ formatEventDetailsJson(currentEvent.event_details) }}</pre>
                  </el-collapse-item>
                </el-collapse>
              </div>
            </div>
          </div>

          <div slot="footer" class="dialog-footer">
            <el-button @click="eventDetailsVisible = false">关闭</el-button>
            <el-button
              v-if="currentEvent && currentEvent.handle_status === 'unhandled'"
              type="primary"
              @click="markEventAsHandled(currentEvent, true)"
            >标记为已处理</el-button>
          </div>
        </el-dialog>
      </el-tab-pane>
    </el-tabs>
    </el-card>


    <!-- 修复确认对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="30%"
      :close-on-click-modal="false"
      :modal="false"
    >
      <div class="dialog-content">
        <div class="dialog-icon" :class="dialogType">
          <i :class="dialogIcon"></i>
        </div>
        <div class="dialog-message">{{ dialogMessage }}</div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          @click="confirmDialog"
          :loading="dialogLoading"
        >确定</el-button>
      </div>
    </el-dialog>

    <!-- 漏洞详情对话框 -->
    <el-dialog
      direction="rtl"
      title="漏洞详情"
      :visible.sync="detailsVisible"
      width="80%"
      :modal="false"
      :close-on-click-modal="false"
      class="vulnerability-details-dialog"
    >
      <div class="details-header">
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="detail-item">
              <span class="detail-label">漏洞编号：</span>
              <span class="detail-value">{{ currentVulnerability.cveId || '-' }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="detail-item">
              <span class="detail-label">影响分：</span>
              <span class="detail-value">
                <el-tag
                  :type="getScoreType(currentVulnerability.score)"
                  size="small"
                >{{ currentVulnerability.score || 'N/A' }}</el-tag>
              </span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="detail-item">
              <span class="detail-label">发现时间：</span>
              <span class="detail-value">{{ currentVulnerability.lastFound || '-' }}</span>
            </div>
          </el-col>
        </el-row>
      </div>

      <el-tabs v-model="activeTab">
        <el-tab-pane label="相关漏洞" name="related">
          <el-table
            :data="relatedVulnerabilities"
            style="width: 100%"
            border
          >
            <el-table-column prop="cveId" label="漏洞编号" width="150">
              <template slot-scope="scope">
                <el-link type="primary" :underline="false">{{ scope.row.cveId }}</el-link>
              </template>
            </el-table-column>
            <el-table-column prop="score" label="影响分" width="100">
              <template slot-scope="scope">
                <span v-if="scope.row.score">{{ scope.row.score }}</span>
                <span v-else>N/A</span>
              </template>
            </el-table-column>
            <el-table-column prop="description" label="漏洞公告" min-width="400">
              <template slot-scope="scope">
                <div class="vulnerability-description">{{ scope.row.description }}</div>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120" fixed="right">
              <template slot-scope="scope">
                <el-button
                  type="text"
                  @click="handleSuggestion(scope.row)"
                >处理建议</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="处理建议" name="suggestions">
          <div class="suggestions-content">
            <div class="suggestion-section">
              <h4>漏洞描述</h4>
              <p>{{ currentVulnerability.description }}</p>
            </div>
            <div class="suggestion-section">
              <h4>影响范围</h4>
              <p>{{ currentVulnerability.impact || '暂无影响范围信息' }}</p>
            </div>
            <div class="suggestion-section">
              <h4>修复建议</h4>
              <div class="fix-steps">
                <div v-for="(step, index) in currentVulnerability.fixSteps" :key="index" class="fix-step">
                  <div class="step-number">{{ index + 1 }}</div>
                  <div class="step-content">{{ step }}</div>
                </div>
              </div>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="修复记录" name="history">
          <el-timeline>
            <el-timeline-item
              v-for="(activity, index) in fixHistory"
              :key="index"
              :type="activity.type"
              :color="getActivityColor(activity.type)"
              :timestamp="activity.timestamp"
            >
              {{ activity.content }}
            </el-timeline-item>
          </el-timeline>
        </el-tab-pane>
      </el-tabs>

      <div slot="footer" class="dialog-footer">
        <el-button @click="detailsVisible = false">关闭</el-button>
        <el-button
          type="primary"
          @click="handleFix(currentVulnerability)"
          :disabled="currentVulnerability.status === '修复成功'"
        >立即修复</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import {baseline, security, statistics, vulnerability,events} from '@/api/resell/orderinstance'

export default {
  name: 'HostSecurity',
  props: {
    currentResource: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      loading: false,
      urgencyLevel: 'all',
      status: 'all',
      searchQuery: '',
      total: 0,
      securityScoreChart: null,
      vulnerabilities: [],
      selectedVulnerabilities: [],
      dateRange: [],
      dialogVisible: false,
      dialogTitle: '',
      dialogMessage: '',
      dialogType: '',
      dialogIcon: '',
      dialogLoading: false,
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          }
        ]
      },
      detailsVisible: false,
      activeTabs: 'config',
      activeTab: 'related',
      currentVulnerability: {},
      relatedVulnerabilities: [],
      fixHistory: [
        {
          timestamp: '2024-04-23 14:30:00',
          content: '系统自动检测到新漏洞',
          type: 'warning'
        },
        {
          timestamp: '2024-04-23 14:35:00',
          content: '已生成修复方案',
          type: 'info'
        },
        {
          timestamp: '2024-04-23 15:00:00',
          content: '开始执行修复',
          type: 'primary'
        }
      ],
      localCurrentResource: {},
      needUrgentRepair:null,// 需紧急修复的漏洞数
      unrepair:null,// 未完成修复的漏洞数
      existedVulHosts:null,// 存在漏洞的服务器数
      todayHandle:null,//今日处理漏洞数
      allHandle:null,//累计处理漏洞数
      supported:null,//已支持漏洞数
      vulLibraryUpdateTime:null,//漏洞库更新时间
      queryParams: {
        pageNum: 1,
        pageSize: 10
      },
      securityEvents: [],
      selectedEvents: [],
      securityLevel: 'all',
      handleStatus: 'all',
      eventSearchQuery: '',
      eventsLoading: false,
      eventDetailsVisible: false,
      currentEvent: null,
      eventPagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
    }
  },
  created() {
    this.localCurrentResource = this.currentResource;  // 初始化本地数据属性
    this.getList();
  },
  computed: {
    filteredVulnerabilities() {
      let result = [...this.vulnerabilities]

      if (this.urgencyLevel !== 'all') {
        result = result.filter(item => item.urgencyLevel === this.urgencyLevel)
      }

      if (this.status !== 'all') {
        result = result.filter(item => item.status === this.status)
      }

      if (this.searchQuery) {
        const query = this.searchQuery.toLowerCase()
        result = result.filter(item =>
          item.name.toLowerCase().includes(query)
        )
      }

     // this.total = result.length
      return result
    },
    filteredSecurityEvents() {
      if (!this.securityEvents || !Array.isArray(this.securityEvents)) {
        return [];
      }

      let result = [...this.securityEvents];

      // 按告警级别过滤
      if (this.securityLevel !== 'all') {
        result = result.filter(event => event.severity === this.securityLevel);
      }

      // 按处理状态过滤
      if (this.handleStatus !== 'all') {
        result = result.filter(event => event.handle_status === this.handleStatus);
      }

      // 按搜索关键词过滤
      if (this.eventSearchQuery) {
        const query = this.eventSearchQuery.toLowerCase();
        result = result.filter(event =>
          (event.event_name && event.event_name.toLowerCase().includes(query)) ||
          (event.host_name && event.host_name.toLowerCase().includes(query)) ||
          (event.private_ip && event.private_ip.includes(query))
        );
      }

      return result;
    }
  },
  methods: {
    getList() {
      // need_urgent_repair 需紧急修复的漏洞数  unrepair 未完成修复的漏洞数 existed_vul_hosts 存在漏洞的服务器数
      // today_handle今日处理漏洞数  all_handle累计处理漏洞数    supported已支持漏洞数     vul_library_update_time漏洞库更新时间
      statistics(this.localCurrentResource)
        .then(response => {
          console.log(response);
          try {
            // 解析外层 JSON
            if (response.code === 200) {
              // 解析内层 msg JSON 字符串
              const innerData = JSON.parse(response.msg);
            //  console.log("解析后的数据:", innerData);
             this.unrepair=innerData.unrepair;
             this.needUrgentRepair=innerData.need_urgent_repair;
             this.existedVulHosts=innerData.existed_vul_hosts;
             this.todayHandle=innerData.today_handle;
             this.allHandle=innerData.all_handle;
             this.supported=innerData.supported;
             this.vulLibraryUpdateTime=innerData.vul_library_update_time;

            } else {
              console.error("接口返回错误码:", outerData.code);
            }
          } catch (error) {
            console.error("解析 response 数据失败:", error);
          }
        });

      this.getVulnerability();
      this.getEvents();

    },
    getVulnerability() {
      this.localCurrentResource.pagesize = this.queryParams.pageSize;
      this.localCurrentResource.pagenum =this.queryParams.pageNum;
      vulnerability(this.localCurrentResource).then(response => {
        console.log(response);
        if(response.code===200) {
          this.total = response.total1
          console.log(this.total);
          this.vulnerabilities = response.rows;
        }
        if(response.code===500) {
          this.$message({
            message: response.msg,
            type: 'error'
          })
        }
      })
    },
    getEvents() {
      this.eventsLoading = true;
      events(this.localCurrentResource).then(response => {
        console.log('Events response:', response);
        if (response.code === 200) {
          this.securityEvents = response.rows || [];
          // 使用 total1 而不是 total，因为您的 JSON 数据中显示 total1 是实际的总数
          this.eventPagination.total = response.total1 || 0;
          console.log('Total events:', this.eventPagination.total);
        } else {
          this.$message.error('获取主机告警数据失败');
        }
        this.eventsLoading = false;
      }).catch(error => {
        console.error('获取主机告警数据失败:', error);
        this.$message.error('获取主机告警数据失败');
        this.eventsLoading = false;
        this.securityEvents = [];
      });
    },
    // 标签页切换
    handleTabClick(tab) {
      console.log(tab.name)
    },
    formatTime(timestamp) {
      if (!timestamp) return '';
      const date = new Date(timestamp);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');

      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    initSecurityScore() {
      this.securityScoreChart = echarts.init(this.$refs.securityScore)
      this.updateSecurityScore()
    },
    updateSecurityScore() {
      const option = {
        series: [
          {
            type: 'gauge',
            startAngle: 90,
            endAngle: -270,
            pointer: {
              show: false
            },
            progress: {
              show: true,
              overlap: false,
              roundCap: true,
              clip: false,
              itemStyle: {
                color: '#67C23A'
              }
            },
            axisLine: {
              lineStyle: {
                width: 10
              }
            },
            splitLine: {
              show: false
            },
            axisTick: {
              show: false
            },
            axisLabel: {
              show: false
            },
            data: [
              {
                value: 96,
                name: '',
                title: {
                  offsetCenter: ['0%', '-10%']
                },
                detail: {
                  offsetCenter: ['0%', '10%']
                }
              }
            ],
            title: {
              fontSize: 14
            },
            detail: {
              width: 50,
              height: 14,
              fontSize: 28,
              color: '#67C23A',
              formatter: '{value}分\n安全'
            }
          }
        ]
      }
      this.securityScoreChart.setOption(option)
    },
    handleResourceChange(newResource) {
      // 更新本地资源并通知父组件
      this.$emit('updateCurrentResource', newResource);
      this.localCurrentResource = newResource;

      // 刷新相关数据
      this.refreshData();
    },
    getUrgencyType(level) {
      const types = {
        'Critical': 'danger',
        'High': 'warning',
        'Medium': 'info',
        'Low': ''
      }
      return types[level] || ''
    },
    getUrgencyName(level) {
      const types = {
        'Critical': '紧急',
        'High': '高',
        'Medium': '中',
        'Low': '低'
      }
      return types[level] || ''
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 0
      this.refreshData();
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.refreshData();
    },
    handleFix(row) {
      this.$message({
        type: 'success',
        message: `正在修复漏洞: ${row.name}`
      })
    },
    handleDetails(row) {
      this.currentVulnerability = {
        ...row,
        cveId: 'CVE-2024-2173',
        score: '7.5',
        description: 'Google Chrome wasm-to-js out-of-bounds access vulnerability affects memory safety.',
        impact: '该漏洞影响 Google Chrome 浏览器的内存安全机制，可能导致远程代码执行或程序崩溃。',
        fixSteps: [
          '更新 Google Chrome 浏览器至最新版本',
          '确认更新后的版本号不低于 122.0.6261.111',
          '重启浏览器完成修复'
        ]
      }
      this.detailsVisible = true
      this.activeTab = 'related'
    },
    handleResize() {
      this.securityScoreChart && this.securityScoreChart.resize()
    },
    handleSelectionChange(selection) {
      this.selectedVulnerabilities = selection
    },
    handleBatchFix() {
      this.dialogTitle = '批量修复确认'
      this.dialogMessage = `确定要修复选中的 ${this.selectedVulnerabilities.length} 个漏洞吗？`
      this.dialogType = 'warning'
      this.dialogIcon = 'el-icon-warning'
      this.dialogVisible = true
    },
    exportData() {
      this.$message({
        type: 'success',
        message: '正在导出数据，请稍候...'
      })
    },
    refreshData() {
      this.getList();
      this.$message.success('刷新成功');
    },

    getStatusType(status) {
      const types = {
        '未修复': 'danger',
        '修复成功': 'success',
        '修复失败': 'warning'
      }
      return types[status] || 'info'
    },
    getStatusIcon(status) {
      const icons = {
        '未修复': 'el-icon-warning',
        '修复成功': 'el-icon-success',
        '修复失败': 'el-icon-error'
      }
      return icons[status] || 'el-icon-info'
    },
    handleMore(command, row) {
      const actions = {
        ignore: '已忽略漏洞',
        report: '问题已报告',
        history: '查看修复历史'
      }
      this.$message({
        type: 'success',
        message: actions[command]
      })
    },
    confirmDialog() {
      this.dialogVisible = false
    },
    getActivityColor(status) {
      const colors = {
        '未修复': '#F56C6C',
        '修复成功': '#67C23A',
        '修复失败': '#E6A23C'
      }
      return colors[status] || ''
    },
    handleSuggestion() {
      this.$message({
        type: 'info',
        message: '查看修复建议'
      })
    },
    getScoreType(score) {
      const types = {
        'A': 'success',
        'B': 'warning',
        'C': 'info',
        'D': ''
      }
      return types[score] || ''
    },
    getSeverityType(severity) {
      const types = {
        'Critical': 'danger',
        'High': 'danger',
        'Medium': 'warning',
        'Low': 'info'
      }
      return types[severity] || 'info'
    },
    getSeverityName(severity) {
      const names = {
        'Critical': '严重',
        'High': '高危',
        'Medium': '中危',
        'Low': '低危'
      };
      return names[severity] || severity;
    },
    getOsInfo(row) {
      if (row.resource_info && row.resource_info.length > 0) {
        const resource = row.resource_info[0];
        if (resource.os_type) {
          return `${resource.os_type} ${resource.os_version || ''}`;
        }
      }
      return row.os_type || '未知';
    },
    formatEventTime(timestamp) {
      if (!timestamp) return '--';
      const date = new Date(timestamp);
      return date.toLocaleString();
    },
    formatEventDetailsJson(details) {
      if (!details) return '{}';
      try {
        // 处理双引号问题
        const fixedJson = details.replace(/\"\"/g, '"');
        const obj = JSON.parse(fixedJson);
        return JSON.stringify(obj, null, 2);
      } catch (e) {
        return details;
      }
    },
    markEventAsHandled(event, isHandled) {
      // 实现标记事件为已处理或未处理的逻辑
      console.log('标记事件为已处理:', event, isHandled);
    },
    ignoreEvent(event) {
      // 实现忽略事件的逻辑
      console.log('忽略事件:', event);
    },
    viewEventDetails(event) {
      // 实现查看事件详情的逻辑
      this.currentEvent = event;
      this.eventDetailsVisible = true;
    },
    refreshEvents() {
      this.getEvents();
    },
    batchMarkAsHandled() {
      // 实现批量标记事件为已处理的逻辑
      console.log('批量标记事件为已处理');
    },
    handleEventSelectionChange(selection) {
      this.selectedEvents = selection;
    },
    handleEventSizeChange(size) {
      this.eventPagination.pageSize = size;
      this.getEvents();
    },
    handleEventCurrentChange(page) {
      this.eventPagination.currentPage = page;
      this.getEvents();
    },
  },
  mounted() {
    this.$nextTick(() => {
      this.initSecurityScore()
      window.addEventListener('resize', this.handleResize)
    })
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize)
    this.securityScoreChart && this.securityScoreChart.dispose()
  }
}
</script>

<style scoped>

.security-status {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  margin-bottom: 20px;
  display: flex;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.05);
}

.status-left {
  flex: 1;
  padding-right: 40px;
}

.status-right {
  width: 200px;
}

.security-score {
  height: 200px;
}

.section-title {
  margin: 20px 0 20px 0;
  font-size: 16px;
  color: #303133;
  display: flex;
  align-items: center;
  gap: 8px;
}

.section-title i {
  font-size: 18px;
}

.status-item {
  margin-bottom: 16px;
  display: flex;
  align-items: center;
}

.item-label {
  color: #606266;
  margin-right: 8px;
}

.item-value {
  color: #303133;
}

.mt-20 {
  margin-top: 20px;
}

.vulnerability-section {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.05);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.filter-bar {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-left {
  display: flex;
  gap: 12px;
}

.filter-right {
  width: 250px;
}

.vulnerability-name {
  color: #409EFF;
  cursor: pointer;
}

.vulnerability-name:hover {
  text-decoration: underline;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 原有样式保持不变，添加新的样式 */

.stat-cards {
  margin-bottom: 20px;
}

.stat-card {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  display: flex;
  align-items: center;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.05);
  transition: all 0.3s;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px 0 rgba(0,0,0,0.1);
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 8px;
  background: #f5f7fa;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
}

.stat-icon i {
  font-size: 24px;
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  line-height: 1;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.stat-trend {
  display: flex;
  align-items: center;
  font-size: 12px;
  padding: 2px 6px;
  border-radius: 4px;
}

.stat-trend.up {
  color: #F56C6C;
  background: #fef0f0;
}

.stat-trend.down {
  color: #67C23A;
  background: #f0f9eb;
}

.stat-trend.stable {
  color: #909399;
  background: #f4f4f5;
}

.stat-trend i {
  margin-right: 4px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.count-tag {
  transform: scale(0.9);
}

.status-info {
  color: #909399;
  margin-left: 4px;
  cursor: help;
}

.warning {
  color: #E6A23C;
}

.new-tag {
  margin-left: 8px;
  transform: scale(0.8);
}

.dialog-content {
  text-align: center;
  padding: 20px 0;
}

.dialog-icon {
  font-size: 48px;
  margin-bottom: 20px;
}

.dialog-icon.warning i {
  color: #E6A23C;
}

.dialog-icon.success i {
  color: #67C23A;
}

.dialog-icon.danger i {
  color: #F56C6C;
}

.dialog-message {
  color: #606266;
  font-size: 16px;
}

.security-trend {
  margin-top: 20px;
}

/* 响应式优化 */
@media screen and (max-width: 1400px) {
  .stat-cards .el-col {
    margin-bottom: 20px;
  }
}

@media screen and (max-width: 768px) {
  .stat-card {
    margin-bottom: 10px;
  }

  .section-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }

  .header-right {
    width: 100%;
  }

  .header-right .el-button-group {
    display: flex;
    width: 100%;
  }

  .header-right .el-button {
    flex: 1;
  }
}
.vulnerability-details-dialog {
  min-width: 800px;
}

.details-header {
  padding-bottom: 20px;
  border-bottom: 1px solid #EBEEF5;
  margin-bottom: 20px;
}

.detail-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.detail-label {
  color: #909399;
  margin-right: 8px;
}

.detail-value {
  color: #303133;
  font-weight: 500;
}

.vulnerability-description {
  line-height: 1.5;
  color: #303133;
}

.suggestions-content {
  padding: 20px;
  background: #f5f7fa;
  border-radius: 4px;
}

.suggestion-section {
  margin-bottom: 24px;
}

.suggestion-section h4 {
  margin: 0 0 12px 0;
  font-size: 14px;
  color: #303133;
}

.suggestion-section p {
  margin: 0;
  line-height: 1.6;
  color: #606266;
}

.fix-steps {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.fix-step {
  display: flex;
  align-items: flex-start;
  gap: 12px;
}

.step-number {
  width: 24px;
  height: 24px;
  border-radius: 12px;
  background: #409EFF;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  flex-shrink: 0;
}

.step-content {
  flex: 1;
  line-height: 24px;
  color: #606266;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-timeline-item__node--normal) {
  left: -1px;
}

:deep(.el-timeline-item__wrapper) {
  padding-left: 28px;
}

:deep(.el-timeline-item__content) {
  color: #606266;
}

:deep(.el-timeline-item__timestamp) {
  color: #909399;
}

@media screen and (max-width: 768px) {
  .vulnerability-details-dialog {
    width: 95% !important;
    margin: 0 auto;
  }

  .details-header .el-col {
    width: 100%;
  }

  .fix-step {
    flex-direction: column;
    gap: 8px;
  }

  .step-content {
    padding-left: 36px;
  }
}

/* 表格卡片样式 */
.table-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

/* 修改主机信息样式 */
.host-info {
  display: flex;
  flex-direction: column;
}

.host-name {
  font-weight: 500;
  color: #409EFF; /* 蓝色 */
  margin-bottom: 4px;
}

.host-ip {
  color: #909399;
  font-size: 12px;
  display: block; /* 确保换行 */
}

</style>
